<template>
    <div class="app-container">
        <el-card>
            <!-- 搜索区域 -->
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="订单编号" prop="orderNo">
                    <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable />
                </el-form-item>
                <el-form-item label="收件人" prop="addressee">
                    <el-input v-model="queryParams.orderNo" placeholder="请输入收件人名称" clearable />
                </el-form-item>
                <el-form-item label="店铺名称" prop="customerId" style="width: 200px">
                    <el-select v-model="queryParams.customerId" placeholder="请选择店铺名称" clearable>
                        <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单日期">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                    <el-button type="primary" @click="handleAdd">新增销售单</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格区域改为卡片式布局 -->
            <div class="order-list">
                <div v-for="item in orderList" :key="item.id" class="order-item">
                    <div class="order-header">
                        <div class="order-info">
                            <span class="order-code">订单编号：{{ item.orderNo }}</span>
                            <span class="order-date">{{ item.salesOrderDate }}</span>
                        </div>
                        <div class="order-status">
                            <el-tag :type="item.salesType === 'ONLINE' ? 'success' : 'warning'">
                                {{ item.salesType === "ONLINE" ? "网上销售" : "销售单" }}
                            </el-tag>
                        </div>
                    </div>

                    <el-row class="order-content">
                        <el-col :span="16" class="goods-list">
                            <div v-for="(good, index) in item.items" :key="index" class="goods-item">
                                <div class="goods-image-box">
                                    <el-image :src="good.imageUrl || defaultImage" :preview-src-list="[good.imageUrl]"
                                        class="goods-image" fit="cover" style="width: 120px; height: auto;">
                                        <template #error>
                                            <div class="image-placeholder">
                                                <el-icon>
                                                    <Picture />
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                    <div class="goods-info">
                                        <div class="goods-code">编码：{{ good.productCode }}</div>
                                        <div class="goods-name">商品名称：{{ good.productName }}</div>
                                        <div class="goods-spec">规格：{{ good.specifications }}</div>
                                        <div class="goods-addressee">收件人：{{ good.addressee }}</div>
                                    </div>
                                </div>

                                <div class="goods-benjin">
                                    进价：¥{{ good.purchasePrice?.toFixed(2) }}
                                </div>
                                <div class="goods-quantity">
                                    数量：{{ good.quantity }} /{{ good.unit }}
                                </div>
                                <div class="goods-price">
                                    <div class="selling-price">售价：¥{{ good.sellingPrice?.toFixed(2) }}</div>
                                    <div class="total-price">
                                        小计：¥{{ good.totalPrice?.toFixed(2) }}
                                    </div>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="2" class="warehouse-info">
                            <span>店铺：{{ getCustomerName(item.customerId) }}</span>
                        </el-col>
                        <el-col :span="4" class="amount-info">
                            <span class="amount">销售总金额：¥{{ item.totalAmount?.toFixed(2) }}</span>
                            <span class="freight">（运费：¥{{ item.freight?.toFixed(2) || 0 }}）</span>
                            <span class="profit">利润：¥{{ item.totalProfit?.toFixed(2) }}</span>
                        </el-col>
                        <el-col :span="2" class="operations">
                            <el-button type="danger" @click="handleDelete(item)">删除</el-button>
                        </el-col>
                    </el-row>
                </div>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="current" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
        <!-- 添加/编辑对话框 -->
        <el-dialog :title="title" v-model="open" style="width: 90%;" append-to-body>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="订单编号" prop="orderNo" style="width: 100%">
                            <el-input v-model="form.orderNo" placeholder="请输入订单编号,为空自动生成" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺名称" prop="customerId" style="width: 100%">
                            <el-select v-model="form.customerId" placeholder="请选择店铺名称" clearable>
                                <el-option v-for="item in shopList" :key="item.id" :label="item.shopName"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="销售日期" prop="salesOrderDate">
                            <el-date-picker v-model="form.salesOrderDate" type="datetime" placeholder="请选择销售日期"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="5">
                        <el-form-item label="运费" prop="freight">
                            <el-input-number v-model="form.freight" :precision="2" :step="0.1" :min="0"
                                style="width: 100%;" @change="calculateTotal" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="商品信息">
                    <el-button type="primary" @click="handleAddProduct">添加商品</el-button>
                    <el-table :data="form.items" style="margin-top: 10px">
                        <el-table-column type="index" label="序号" width="100" align="center" />
                        <el-table-column label="商品编码" prop="productCode" width="170">
                            <template #default="{ row }">
                                <el-input v-model="row.productCode" placeholder="请输入商品编码"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="商品名称" prop="productName" width="170">
                            <template #default="{ row }">
                                <el-input v-model="row.productName" placeholder="请输入商品名称"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="收件人" prop="addressee" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.addressee" placeholder="请输入收件人"/>
                            </template>
                        </el-table-column>
                        
                        <el-table-column label="商品图片" width="170">
                            <template #default="scope">
                                <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
                                    :class="{ disabled: scope.row.fileList.length >= 1 }"
                                    :file-list="scope.row.fileList || []"
                                    @change="(file, files) => checkImageFormat(file, files, scope.row)">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                    <template #file="{ file }">
                                        <div>
                                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                            <span class="el-upload-list__item-actions">
                                                <span class="el-upload-list__item-preview"
                                                    @click="handlePictureCardPreview(file)">
                                                    <el-icon><zoom-in /></el-icon>
                                                </span>
                                                <span v-if="!disabled" class="el-upload-list__item-delete"
                                                    @click="handleRemove(file, scope.row)">
                                                    <el-icon>
                                                        <Delete />
                                                    </el-icon>
                                                </span>
                                            </span>
                                        </div>
                                    </template>
                                </el-upload>
                            </template>
                        </el-table-column>
                        <el-table-column label="规格" prop="specifications" width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.specifications" placeholder="请输入规格"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="单位" prop="unit" width="100">
                            <template #default="{ row }">
                                <el-input v-model="row.unit" placeholder="请输入单位"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="进价" width="180">
                            <template #default="{ row }">
                                <el-input-number v-model="row.purchasePrice" :precision="2" :step="0.1" :min="0"
                                    style="width: 100%;" @change="calculateTotal" />
                            </template>
                        </el-table-column>
                        <el-table-column label="售价" width="180">
                            <template #default="{ row }">
                                <el-input-number v-model="row.sellingPrice" :precision="2" :step="0.1"
                                    @change="calculateTotal" :min="0" style="width: 100%;"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="数量" width="160">
                            <template #default="{ row }">
                                <el-input-number v-model="row.quantity" :min="1" 
                                    @change="calculateTotal" style="width: 100%;" />
                            </template>
                        </el-table-column>
                        <el-table-column label="小计" width="150">
                            <template #default="{ row }">
                                ¥{{ (row.sellingPrice * row.quantity)?.toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80">
                            <template #default="{ $index }">
                                <el-button type="text" @click="handleRemoveProduct($index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="总金额">
                    <span class="total-amount">¥{{ form.totalAmount?.toFixed(2) }}</span>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
                        <!-- 图片预览 -->
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image"  width="100%" height="100%"/>
            </el-dialog>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
    fetchProductList,
    fetchWarehouseList,
    fetchShopList,
    createDate
} from "../../../utils/commonMethods";
import { salesOrderApi,uploadApi,stockInApi } from "../../../api";
// 是否为加载中
const loading = ref(false);
//当前页面
const current = ref(1)
//每页条数
const pageSize = ref(10)
//总条数
const total = ref(0)
// 订单列表
const orderList = ref([]);
// 是否打开对话框
const open = ref(false);
// 对话框标题
const title = ref("");
// 日期范围
const dateRange = ref([]);
// 商品列表
const productOptions = ref([]);
// 表单引用
const formRef = ref(null);
// 店铺列表
const shopList = ref([]);
// 图片预览
const dialogVisible = ref(false);
const dialogImageUrl = ref('');


// 删除图片
const handleRemove = (file, row) => {
    // 清空当前行的文件列表
    row.fileList = []
    // 清空图片相关的其他数据
    row.imageUrl = ''
}
// 检查图片格式
const checkImageFormat = (uploadFile, uploadFiles, row) => {

    // 确保每行有 fileList 数组
    if (!row.fileList) {
        row.fileList = []
    }
    row.fileList = uploadFiles.slice(-1)
}
// 图片预览
const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}


// 生成销售单号
const generateSalesOrderCode = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const random = Math.floor(Math.random() * 10000)
        .toString()
        .padStart(4, "0");
    return `CK${year}${month}${day}${random}`;
};
//订单编号
const orderNo = ref("");
// 获取商品列表
const getProductList = async () => {
    productOptions.value = await fetchProductList();
};
// 仓库列表
const warehouseList = ref([]);
// 获取仓库列表
const getWarehouseList = async () => {
    warehouseList.value = await fetchWarehouseList();
};
// 获取店铺列表
const getShopList = async () => {
    shopList.value = await fetchShopList();
    console.log(shopList.value,'shopList.value');
    
};
// 获取店铺名称
const getCustomerName = (customerId) => {
    const customer = shopList.value.find((item) => item.id === customerId);
    return customer ? customer.shopName : "-";
};

// 查询参数
const queryParams = reactive({
    current: 1,
    pageSize: 10,
    orderNo: "",
    customerId: "",
    startDate: "",
    endDate: "",
});

// 表单参数
const form = reactive({
    id: undefined,
    orderNo: "",
    customerId: 3,
    items: [],
    salesOrderDate: new Date(+new Date() + 8 * 3600 * 1000).toISOString().slice(0, 19).replace("T", " "),
    totalAmount: 0,
    freight: 0,
    remark: "",
    warehouseId: undefined,
});

// 表单校验规则
const rules = {
    customerId: [
        { required: true, message: "请选择店铺名称", trigger: "change" },
    ],
    salesOrderDate: [
        { required: true, message: "请选择销售日期", trigger: "change" },
    ],


};

// 查询列表
const getList = async () => {
    loading.value = true;
    try {
        queryParams.current = current.value;
        queryParams.pageSize = pageSize.value;
        if (dateRange.value && dateRange.value.length === 2) {
            queryParams.startDate = dateRange.value[0];
            queryParams.endDate = dateRange.value[1];
        }
        const res = await salesOrderApi.getList(queryParams);

        orderList.value = res.data.records;
        orderList.value.forEach(item => {
            item.items.forEach(good => {
                good.imageUrl = import.meta.env.VITE_API_URL + good.imageUrl
            })
        })
        
        total.value = res.data.total;
    } catch (error) {
        console.error("获取订单列表失败:", error);
    } finally {
        loading.value = false;
    }
};

// 表单重置
const reset = () => {
    form.id = undefined;
    form.orderNo = orderNo.value;
    form.customerId = 3;
    form.items = [];
    form.salesOrderDate = new Date(+new Date() + 8 * 3600 * 1000).toISOString().slice(0, 19).replace("T", " ");
    form.totalAmount = 0;
    form.freight = 0;
    form.remark = "";
};


// 添加商品行
const handleAddProduct = () => {
    form.items.push({
        productId: undefined,
        productName: "",
        addressee: "",
        purchasePrice: 0,
        sellingPrice: 0,
        specifications: "",
        unit: "件",
        quantity: 1,
        totalQuantity: 1,
        imageUrl: "",
        fileList: [],
    });
};

// 删除商品行
const handleRemoveProduct = (index) => {
    form.items.splice(index, 1);
    calculateTotal();
};

// 计算总金额
const calculateTotal = () => {
    form.totalAmount = form.items.reduce((total, item) => {
        return total + item.sellingPrice * item.quantity;
    }, 0) + form.freight;
};

// 提交表单
const submitForm = async () => {
    if (!form.items.length) {
        ElMessage.warning("请至少添加一个商品");
        return;
    }
    if (!formRef.value) return;
    await formRef.value.validate(async (valid) => {
        if (!valid) return;
        try {
            let flag = true
            for(const item of form.items) {
                const formDataUpload = new FormData()
                // 使用 raw 属性获取原始文件对象
                const file = item.fileList[0].raw
                formDataUpload.append('file', file)
                // 上传图片
                const res = await uploadApi.upload(formDataUpload)
                if (res.code !== 200) {
                    ElMessage.error('图片上传失败')
                    flag = false
                    return
                }
                item.imageUrl = res.data
            }
            if (!flag) return
            if (form.id) {
                await salesOrderApi.update(form);
            } else {
                if(!form.orderNo) {
                    form.orderNo = generateSalesOrderCode();
                }
                await salesOrderApi.create(form);
            }
            ElMessage.success("保存成功");
            open.value = false;
            getList();
            reset();
        } catch (error) {
            console.error("保存失败:", error);
        }
    });
};

// 其他操作处理函数
const handleQuery = () => {
    queryParams.current = 1;
    getList();
};

const resetQuery = () => {
    dateRange.value = [];
    Object.assign(queryParams, {
        current: 1,
        pageSize: 10,
        orderNo: "",
        customerId: "",
        startDate: "",
        endDate: "",
    });
    handleQuery();
};
//取消
const cancel = () => {
    open.value = false;
    reset();
};

// 添加销售单
const handleAdd = () => {
    reset();
    open.value = true;
    title.value = "添加销售单";
};

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val;
    getList();
}

const handleCurrentChange = (val) => {
    current.value = val;
    getList();
}

// 删除销售单
const handleDelete = async (row) => {
    ElMessageBox.confirm("确认要删除该销售单吗？", "警告", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
    }).then(async () => {
        console.log(row);
        
        ElMessageBox.confirm("请选择是否加入到库存", "提示", {
        type: "warning",
        confirmButtonText: "加入到库存",
        cancelButtonText: "不加入到库存",
    })
    .then(async () => {
        try {
            // 加入到库存
            await salesOrderApi.delete(row.id);
            await ceateStockIn(row);
            ElMessage.success("删除成功");
            getList();
        } catch (error) {
            console.error("删除失败:", error);
        }
        
    }).catch(async() => {
        // 不加入到库存
        try {
            // 不加入到库存
            await salesOrderApi.delete(row.id);
            ElMessage.success("删除成功");
            getList();
        } catch (error) {
            console.error("删除失败:", error);
        }
        return
    })
    })
    
};
// 生成入库单号
const generateStockInCode = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const random = Math.floor(Math.random() * 10000)
        .toString()
        .padStart(4, "0");
    return `SI${year}${month}${day}${random}`;
};
const ceateStockIn = async (row) => {
    const formData = {
        stockInCode: generateStockInCode(),
        stockInType: "RETURN",
        warehouseId: row.customerId,
        stockInDate: createDate(), // 格式：YYYY-MM-DD HH:mm:ss
        remark: "",
        items: [],
        totalAmount: 0,
    }
    formData.items = row.items.map(item => {
        const amount =Number(item.quantity)  * Number(item.purchasePrice) 
        formData.totalAmount += amount;
        return {
            imageUrl: new URL(item.imageUrl).pathname,
            productCode: item.productCode,
            productName: item.productName,
            specifications: item.specifications,
            unit: item.unit,
            quantity: item.quantity,
            purchasePrice: item.purchasePrice,
            amount: amount
        }
        
    })
    
    await stockInApi.create(formData);
}



onMounted(() => {
    getList();
    getProductList();
    getWarehouseList();
    getShopList();
});
</script>

<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card {
    display: none !important;
}
.order-list {
    .order-item {
        background: #fff;
        border-radius: 4px;
        margin-bottom: 16px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        .order-header {
            padding: 16px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .order-info {
                .order-code {
                    font-weight: bold;
                    margin-right: 24px;
                }

                .order-date {
                    color: #999;
                }
            }
        }

        .order-content {
            padding: 16px;
        }
    }
}

.goods-list {
    margin: 16px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 20px;
    color: #666;
    font-size: 14px;

    .goods-image-box {
        display: flex;
        align-items: center;
    }

    .goods-info {
        margin: 0 16px;
    }

    .goods-benjin {
        margin: 0 16px;
    }

    .goods-quantity {
        margin: 0 16px;
    }

    .goods-price {
        margin: 0 16px;
        text-align: right;

        .selling-price {
            color: #007bff;
            font-size: 14px;
        }

        .total-price {
            color: #f56c6c;
            font-weight: bold;
            font-size: 16px;
        }
    }

}

.goods-item {
    display: flex;
    justify-content: space-between;
    width: 100%;
    align-items: center;

    padding: 12px 0;

    &:first-child {}

    &:not(:last-child) {
        border-bottom: 1px dashed #f0f0f0;
    }
}

.goods-image {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    margin-right: 16px;
}

.warehouse-info {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin: 16px 0;
    padding: 16px 0;
    border: 1px solid #f0f0f0;
    border-right: none;
    text-align: center;
    color: #666;
}

.amount-info {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px solid #f0f0f0;
    padding: 16px 0;
    margin: 16px 0;

    .amount {
        font-size: 16px;
        color: #f56c6c;
        font-weight: bold;
        margin-bottom: 8px;
    }

    .freight {
        font-size: 12px;
        color: #999;
        margin-bottom: 8px;
    }

    .profit {
        font-size: 14px;
        color: #67C23A;
    }
}

.operations {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    border: 1px solid #f0f0f0;
    padding: 16px 0;
    margin: 16px 0;
    border-left: none;
}

.total-amount {
    font-size: 18px;
    color: #f56c6c;
    font-weight: bold;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>